package com.youhong.teethcare.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.MainActivity;
import com.youhong.teethcare.javabeans.BrushingRecord;
import com.youhong.teethcare.receiver.TimerService;
import com.youhong.teethcare.services.Common;

import java.util.Calendar;

import retrofit2.http.PUT;

public class DataReceiverUtils {
    Context context;
    DBHelper dbHelper;
    private static DataReceiverUtils dataReceiverUtils;

    public static void init(Context context) {
        if (dataReceiverUtils == null) {
            synchronized (DataReceiverUtils.class) {
                if (dataReceiverUtils == null) {
                    dataReceiverUtils = new DataReceiverUtils(context);
                }
            }
        }
    }

    public static DataReceiverUtils getInstance() {
        return dataReceiverUtils;
    }

    private DataReceiverUtils(Context context) {
        this.context = context;
        dbHelper = DBHelper.getDbHelper(context);
        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        filter.addAction(BleService.ACTION_onDescriptorWrite);
        context.registerReceiver(receiver, filter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BleService.ACTION_DATA_AVAILABLE)) {
                byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);
                resloveData(values);
            } else if (action.equals(BleService.ACTION_onDescriptorWrite)) {

            }

        }
    };
    int score=0;
    long lastSyncTime=0;
    //绑定牙刷进行同步时，1.获取电量 ,2.获取刷牙时长,3.同步历史数据
    private void resloveData(byte[] values) {

        if (values[0] == DeviceCmd. Cmd_GetDeviceBattery) {
            Common.battery = values[1] & 0xFF;
            if(lastSyncTime==0||System.currentTimeMillis()-lastSyncTime>60*1000*2){
                MainActivity.mDevice.getBrushingTime();
            }else{
                MainActivity.mDevice.getVersion();
            }


        } else if (values[0] == DeviceCmd.Cmd_GetBrushTime) {

            Common.userInfo.setBrushTime(values[1] + values[2] + values[3] + values[4]);
            Common.userInfo.SyncToLocal(context);
            MainActivity.mDevice.getHand();

        } else if (values[0] == DeviceCmd.Cmd_GetHand) {

            int hand = values[1] & 0xFF;
            if (hand == 1) {
                //左手
                Common.userInfo.setHand(0x1);
            } else {
                //右手
                Common.userInfo.setHand(0x0);
            }

            Common.userInfo.SyncToLocal(context);
            MainActivity.mDevice.getBrushingData((byte) 0x0);

        } else if (values[0] ==DeviceCmd.Cmd_GetBrushHistoryRecord) {

            //结束标识符
            if (values[1] == (byte) 0xFF) {
                score=0;
                //刷新最新数据时间戳
               lastSyncTime=System.currentTimeMillis();
                MainActivity.mDevice.getVersion();
                return;
            }
            Calendar data_c = Calendar.getInstance();

            int year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0;
            //0为离线刷牙，1为指导刷牙记录
            int type = 1;
            year = Util.ConvertBCD2Decimal(values[2]) + 2000;
            month = Util.ConvertBCD2Decimal(values[3]) - 1;
            day = Util.ConvertBCD2Decimal(values[4]);

            if (values[5] >= 0x24) {
                //减去0x48
                hours = Util.ConvertBCD2Decimal((byte) (values[5] - 48));
                type = 0;

            } else {
                hours = Util.ConvertBCD2Decimal(values[5]);
            }
            minutes = Util.ConvertBCD2Decimal(values[6]);
            seconds = Util.ConvertBCD2Decimal(values[7]);

            data_c.set(year, month, day, hours, minutes, seconds);

        //    Log.i(TAG, "resloveData:getLastSyncTime "+data_c.getTime().toLocaleString());
            //新的历史记录
            if (data_c.getTimeInMillis() >0) {
                int totalTime = (values[8] & 0xFF) + ((values[9] << 8) & 0xFF00);

                //牙刷中的离线刷牙历史数据，少于30s 的刷牙时间不做存储。
                //大于3分钟也不做存储
                if (type == 1) {
                    if (totalTime < 30 || totalTime > 180) {
                        return;
                    }
                    //离线刷牙时;如果刷满固件所设定的时间:离线刷牙的数据总会多出1~2秒的。
                    if (Common.userInfo.getBrushTime() + 1 == totalTime ||
                            Common.userInfo.getBrushTime() + 2 == totalTime
                    ) {
                        totalTime = Common.userInfo.getBrushTime();
                    }
                    //牙刷中的离线刷牙历史数据，少于30s 的刷牙时间不做存储。
                    //大于5分钟也不做存储
                } else {

                    if (totalTime < 30 || totalTime > 300) {
                        return;
                    }


                }

                BrushingRecord record = new BrushingRecord();
                record.setUid(Common.userInfo.getToken());
                record.setTotalTime(totalTime);
                record.setStartTime(data_c);

                //我这边DBHelper type = 0 是指导刷牙数据,离线刷牙数据是 1
                record.setType(type);//牙刷历史数据

                int area_count = 0;
                if (type == 0) {
                    record.setBrushMode(values[10] & 0xFF);
                    record.setBrushLevel(values[11] & 0xFF);
                    int area1 = 0, area2 = 0, area3 = 0, area4 = 0, area5 = 0, area6 = 0;

                    //下门牙外
                    if (values[20] == 10) {
                        area1 += 1;
                        area_count++;
                    }

                    //下门牙内
                    if (values[21] == 10) {
                        area1 += 4;
                        area_count++;
                    }
                    //上门牙外
                    if (values[22] == 10) {
                        area2 += 1;
                        area_count++;
                    }
                    //上门牙内
                    if (values[23] == 10) {
                        area2 += 4;
                        area_count++;
                    }

                    //左下外
                    if (values[24] == 10) {
                        area3 += 1;
                        area_count++;
                    }

                    //左下中
                    if (values[25] == 10) {
                        area3 += 2;
                        area_count++;
                    }

                    //左下内
                    if (values[26] == 10) {
                        area3 += 4;
                        area_count++;
                    }


                    //左上外
                    if (values[27] == 10) {
                        area4 += 1;
                        area_count++;
                    }

                    //左上中
                    if (values[28] == 10) {
                        area4 += 2;
                        area_count++;
                    }

                    //左上内
                    if (values[29] == 10) {
                        area4 += 4;
                        area_count++;
                    }

                    //右下外
                    if (values[30] == 10) {
                        area5 += 1;
                        area_count++;
                    }

                    //右下中
                    if (values[31] == 10) {
                        area5 += 2;
                        area_count++;
                    }

                    //右下内
                    if (values[32] == 10) {
                        area5 += 4;
                        area_count++;
                    }


                    //右上外
                    if (values[33] == 10) {
                        area6 += 1;
                        area_count++;
                    }

                    //右上中
                    if (values[34] == 10) {
                        area6 += 2;
                        area_count++;
                    }

                    //右上内
                    if (values[35] == 10) {
                        area6 += 4;
                        area_count++;
                    }

                    record.setArea1(area1);
                    record.setArea2(area2);
                    record.setArea3(area3);
                    record.setArea4(area4);
                    record.setArea5(area5);
                    record.setArea6(area6);
                }
                int percent;
                if (type == 1) {
                    percent = (int) ((float) totalTime / (float) Common.userInfo.getBrushTime() * 100);
                } else {

                    percent = (int) ((float) area_count / (float) 16 * 100f);

                }
                //如果超出离线刷牙时长的设置，还是100%
                percent = percent > 100 ? 100 : percent;

                record.setPercent(percent);
                record.setSurfaceCount(area_count);
                dbHelper.insertBrushRecord(record);

                //累加刷牙积分
                float ratio = (float) totalTime / (float) Common.userInfo.getBrushTime();

                if (ratio > 1f) {
                    ratio = 1f;
                }

                //离线刷牙数据统一加10分
                score+=10;
                Common.userInfo.setScore(score);
                Common.userInfo.SyncToLocal(context);
            }
        }else if(values[0] == DeviceCmd.Cmd_GetDeviceVersion) {
           String version = ((values[1] - 0x30) + "." + (values[2] - 0x30) + "."
                    + (values[3] - 0x30) + "." + (values[4] - 0x30));
            Common.userInfo.setDeviceVersion(version);
            Log.i(TAG, "resloveData: "+version);
            Common.userInfo.SyncToLocal(context);
        }else if(values[0]==DeviceCmd.Cmd_SaveData){
            //保存数据后停止刷牙，防止两条数据一起发会导致刷牙无法停止
            MainActivity.mDevice.guideBrushing((byte) 0x0, (byte) 0x0);
        }

    }

    private static final String TAG = "DataReceiverUtils";
}
